package pl.lsierant.j2me.bipacz.player;

import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;

import pl.lsierant.j2me.bipacz.log.Logger;

// FIXME remove hardcoded players
public class PlayerManager {
    private static final Logger logger = new Logger("PlayerManager");
    private Player beep1;
    private Player beep2;
    private Player beep3;

    public PlayerManager() {
        init();
    }

    public void init() {
        beep1 = createPlayer("beep.wav");
        beep2 = createPlayer("beep2.wav");
        beep3 = createPlayer("beep3.wav");
    }

    public void closePlayers() {
        closePlayer(beep1);
        closePlayer(beep2);
        closePlayer(beep3);
    }

    public void closePlayer(Player p) {
        if (p.getState() != Player.CLOSED) {
            logger.log("close player");
            p.close();
        }
    }

    public void playBeep1() {
        playPlayer(beep1);
    }

    public void playBeep2() {
        playPlayer(beep2);
    }

    public void playBeep3() {
        playPlayer(beep3);
    }

    private Player createPlayer(String soundFile) {
        try {
            InputStream stream = getClass().getResourceAsStream("/" + soundFile);
            if (stream == null) {
                logger.log("stream == null");
                return null;
            }
            Player player;
            player = Manager.createPlayer(stream, "audio/x-wav");
            player.addPlayerListener(new PlayerListener() {
                public void playerUpdate(Player arg0, String arg1, Object arg2) {
                    logger.log("playerUpdate: player = " + arg0 + "; arg1 = " + arg1 + "; arg2   = " + arg2);
                }
            });
            player.prefetch();

            VolumeControl vc = (VolumeControl) player.getControl("VolumeControl");
            if (vc != null) {
                vc.setLevel(100);
            }

            player.realize();
            return player;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    private void playPlayer(Player player) {
        if (player == null) {
            logger.log("player == null");
            return;
        }
        logger.log("start player");
        try {
            if (player.getState() == Player.STARTED) {
                player.stop();
            }
            player.prefetch();
            player.start();
        } catch (MediaException e) {
            e.printStackTrace();
            logger.log("play exception: " + e.getMessage());
        }
    }
}
